class Solution
{
    vector<vector<int>> ret;
    int check[200][200] = { 0 };
    int n = 0, m = 0;
public:
    vector<vector<int>> pacificAtlantic(vector<vector<int>>& heights)
    {
        n = heights.size();
        m = heights[0].size();
        for (int i = 0; i < n; ++i)
        {
            if (check[i][0] != 1 && check[i][0] != 3)
                dfs(heights, i, 0, 1);
            if (check[i][m - 1] != 2 && check[i][m - 1] != 3)
                dfs(heights, i, m - 1, 2);
        }
        for (int j = 0; j < m; ++j)
        {
            if (check[0][j] != 1 && check[0][j] != 3)
                dfs(heights, 0, j, 1);
            if (check[n - 1][j] != 2 && check[n - 1][j] != 3)
                dfs(heights, n - 1, j, 2);
        }
        return ret;
    }

    void dfs(vector<vector<int>>& grid, int row, int col, int flag)
    {
        check[row][col] += flag;
        if (check[row][col] == 3)
        {
            vector<int> site = { row, col };
            ret.push_back(site);
        }
        int num = grid[row][col];
        if (row - 1 >= 0 && check[row - 1][col] != flag && grid[row - 1][col] >= num && check[row - 1][col] != 3)
        {
            dfs(grid, row - 1, col, flag);
        }
        if (row + 1 < n && check[row + 1][col] != flag && grid[row + 1][col] >= num && check[row + 1][col] != 3)
        {
            dfs(grid, row + 1, col, flag);
        }
        if (col - 1 >= 0 && check[row][col - 1] != flag && grid[row][col - 1] >= num && check[row][col - 1] != 3)
        {
            dfs(grid, row, col - 1, flag);
        }
        if (col + 1 < m && check[row][col + 1] != flag && grid[row][col + 1] >= num && check[row][col + 1] != 3)
        {
            dfs(grid, row, col + 1, flag);
        }
    }
};